//
//  Dictionary+Ex.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2024/12/20.
//

import Foundation

public extension Dictionary where Key == String {
    
    func safeString(forKey key: String) -> String {
        return safeObject(forKey: key, defaultValue: "")
    }
    
    func safeStringInt(forKey key: String) -> String {
        return safeObject(forKey: key, defaultValue: "0")
    }
    
    func safeArray(forKey key: String) -> [Any] {
        return safeObject(forKey: key, defaultValue: [])
    }
    
    func safeDictionary(forKey key: String) -> [String: Any] {
        return safeObject(forKey: key, defaultValue: [:])
    }
    
    func safeNumber(forKey key: String) -> NSNumber {
        return safeObject(forKey: key, defaultValue: NSNumber(value: 0))
    }
    
    func safeInt(forKey key: String) -> Int {
        guard let value = self[key] , let valueInt = value as? Int else { return 0 }
        return valueInt
    }
    
    func safeObject(forKey key: String) -> Any {
        return safeObject(forKey: key, defaultValue: NSObject())
    }
    
    private func safeObject<T>(forKey key: String, defaultValue: T) -> T {
        guard let value = self[key]  , let valueT = value as? T else { return defaultValue }
        return valueT
    }
}

public extension Dictionary where Key == String {
    /// 将字典转换为 JSON 字符串
    func toJSONString() -> String? {
        do {
            // 将字典转换为 JSON 数据
            let jsonData = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
            
            // 将 JSON 数据转换为字符串
            return String(data: jsonData, encoding: .utf8)
        } catch {
            print("Error converting dictionary to JSON: \(error)")
            return nil
        }
    }
}


extension Dictionary: CustomDebugStringConvertible {
    public var debugDescription: String {
        return (self as NSDictionary).description
    }
}

extension Array: CustomDebugStringConvertible {
    public var debugDescription: String {
        return (self as NSArray).description
    }
}
